<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Support\Facades\Crypt;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

use App\Models\User;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use Redis;

/**
 * 公共控制器
 */
abstract class AdminController extends Controller
{
	 /**
     * Handle a common request to the application.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response
     */
    public function common(Request $request,$methodname)
    {
        // eyJpdiI6ImIreEUrTzExbG9OVVJtbDFwUlhlUHc9PSIsInZhbHVlIjoiRllmNjVKV3R6Yjc3Tno0bWVycWpiUlljbDVSaDlTTkRidEs3aCtcLzhrK1hvc2hCU0ZVdW1nY1ZBRnRoRWhZVkhiblFNMFIxSXh6Y0pKK0FWUkJrc0lRajJZQVZLUGI1eVdFQ0VickNnYkkrclhPQktQUG83M2hCbVFsdklFR0xYcFJ6RjFVeWFMNDljQ0hxY3E0MUY0SkRGUGt3NGRCUlVINGJZQlk5STBWcFJ2QVNDOWtIRkVtbzFIOWRoY3BSSyIsIm1hYyI6IjRkYzRlYWVlZTg0YzBjYmJlYWU5OGVmOTRmZjRmMGJhNzExYTQ0MzAzNGJlMjQzNmFjYjdmMmRmZTY4MTIyYTEifQ==
        //验证方法存在
        if(!method_exists($this, $methodname))
            $result = ['code'=> config('constants.API_METHOD_NOT_EXIST_CODE'),'message'=> config('constants.API_METHOD_NOT_EXIST')];
        else
        {
            //验证请求合法
            $validator = Validator::make($request->all(), $this->rules($methodname));
            if ($validator->fails()) {
                return response()->json(['code'=>config('constants.API_PARAM_ERROR_CODE'),'message'=>$validator->errors()->first()]);
            }
            //token合法
            try{
                $userInfo = json_decode(crypt::decrypt($request->input('token')));
                if(!$userInfo){
                    return response()->json(['code' => config('constants.API_TOKEN_ERROR_CODE'), 'message' => config('constants.API_TOKEN_ERROR')]);
                }
                $result = $this->$methodname($request);
                // token有效期
                // if(Redis::get('userId:'.$userInfo->id)){
                //     Redis::expire('userId:'.$userInfo->id,config('constants.API_TOKEN_EXPIRE_TIME'));
                    
                // }else{
                //     return response()->json(['code' => config('constants.API_TOKEN_ERROR_CODE'), 'message' => config('constants.API_TOKEN_ERROR')]);
                // }
            }catch(\Exception $e){
                return response()->json(['code' => config('constants.API_TOKEN_ERROR_CODE'), 'message' => $e->getMessage()]);
            }
        }
        return response()->json($result);
    }

    /**
     * 抽象方法
     * 验证请求合法规则
     * @return mixed
     */
    abstract protected function rules($methodname);
}
